package yunquan.wang.base.web.data;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.support.RequestContextUtils;
import org.springframework.web.util.WebUtils;

import yunquan.wang.base.config.AppConfig;
import yunquan.wang.base.dao.MatchType;
import yunquan.wang.base.dao.PropertyFilter;
import yunquan.wang.base.web.PageSearch;
import yunquan.wang.base.web.WebConstants;

public class PageSearchArgumentResoler  implements HandlerMethodArgumentResolver{
	public static final String PAGE_NO = "pageNo";
	public static final String PAGE_SIZE = "numPerPage";
	public static final String ORDER_FIELD = "orderField";
	public static final String ORDER_DIRECTION = "orderDirection";
	public static final String PAGESEARCH_KEY="_pageSearch";
	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		if( PageSearch.class.isAssignableFrom(parameter.getParameterType()))
			return true;
		return false;
	}

	@Override
	public Object resolveArgument(MethodParameter parameter,
			ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
			WebDataBinderFactory binderFactory) throws Exception {
		HttpServletRequest request=		(HttpServletRequest)webRequest.getNativeRequest();
		Map<String, ?>  map=	RequestContextUtils.getInputFlashMap(request);
		
		PageSearch pageSearch=null;
		if(map!=null)
		{
			pageSearch=(PageSearch)map.get(PAGESEARCH_KEY);
		}
		else
		{
			pageSearch=new 	PageSearch();
			PageRequest page = null;
			String orderField = request.getParameter(ORDER_FIELD);
			String orderDirection = request.getParameter(ORDER_DIRECTION);
			String pageNo = request.getParameter(PAGE_NO);
			Integer pageInt = StringUtils.isBlank(pageNo) ? 0 : Integer
					.valueOf(pageNo) - 1;
			String pageSize = request.getParameter(PAGE_SIZE);
			Integer sizeInt = StringUtils.isBlank(pageSize) ? AppConfig.getPagesize()
					: Integer.valueOf(pageSize);
			if (StringUtils.isNotBlank(orderDirection)
					&& StringUtils.isNotBlank(orderField)) {
				//
				// 多个排序
				// String[] orders= StringUtils.split(orderDirection);
				// String[] fields= StringUtils.split(orderField);
				// List<Order> orderList=new ArrayList<Order>();
				// for(int i=0;i<orders.length;i++)
				// {
				// Order order=null;
				// if(orders[i].equalsIgnoreCase("DESC"))
				// {
				// order=new Order(Direction.DESC,fields[i]);
				// }
				// else
				// {
				// order=new Order(Direction.ASC,fields[i]);
				// }
				// orderList.add(order);
				// }
				page = new PageRequest(pageInt, sizeInt, new Sort(
						Direction.fromString(orderDirection), orderField));

			} else {
				page = new PageRequest(pageInt, sizeInt);
			}
			pageSearch.setPage(page);
			
			List<PropertyFilter> filterList = new ArrayList<PropertyFilter>();
			//从request中获取含属性前缀名的参数,构造去除前缀名后的参数Map.
			Map<String, Object> filterParamMap = WebUtils.getParametersStartingWith((ServletRequest)webRequest.getNativeRequest(), WebConstants.FILTER_PERFIX + "_");
	 
			//分析参数Map,构造PropertyFilter列表
			for (Map.Entry<String, Object> entry : filterParamMap.entrySet()) {
				
				String value = (String) entry.getValue();
				//如果value值为空,则忽略此filter.
				if (StringUtils.isNotBlank(value)) {
					String filterName = entry.getKey();
					PropertyFilter filter=null ;
					if(filterName.contains("_")){
			      String[] names=filterName.split("_");
			      filter = new PropertyFilter(names[1], Enum.valueOf(MatchType.class, names[0]),value);
					}
					else
					{
						  filter = new PropertyFilter(filterName, value);
					}
					webRequest.setAttribute(filterName.replace(".", "_"), value,0);
					filterList.add(filter);
				}
			}
			pageSearch.setFilters(filterList);
			RequestContextUtils.getOutputFlashMap(request).put(PAGESEARCH_KEY, pageSearch);
		}
		
	
		return pageSearch;
	}

}
